from aiohttp import web

class WebApi(object):
    '''
    web api 类
    '''
    def __init__(self, controller = None):

        self.controller = controller

    async def time(self, request):
        
        return web.Response(text=str(self.controller.now_time))

    async def task_add(self, request):
        
        task = await request.json()

        # 类型转换
        for key, value in task.items():
            if value:
                task[key] = int(value)

        taskid = self.controller.add_tasks(task)
        return web.json_response({
            'taskid': taskid
        })

    async def tasks(self, request):
        '''
        获取当前所有的任务
        '''
        return web.json_response({
            'tasks': self.controller.tasks_info
        })

    async def aivs(self, request):
        '''
        获取当前所有的任务
        '''
        return web.json_response({
            'aivs': self.controller.aivs_info
        })

    async def where_to_go(self, request):
        """
        aiv 迷茫的时候，调用此接口告诉它要往哪儿去
        """
        data = await request.json()

        aiv = data.get('aiv', None)
        signal = data.get('signal', None)

        if not aiv:
            return web.json_response()

        result = self.controller.arrange_one_aiv(aiv, signal)
        return web.json_response(result.info)
        